// 项目的入口文件

// 引入了一些内置的和第三方的模块
var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");

// 引入了两个自定义的路由模块
var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");

// 执行express会得到app对象
var app = express();

// 定义了项目的视图目录为./views目录
app.set("views", path.join(__dirname, "views"));
// 将ejs作为项目的模板引擎
app.set("view engine", "ejs");

// 使用上面引入的内置和第三方模块
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// 指定了public为项目的静态资源目录
app.use(express.static(path.join(__dirname, "public")));

// 使用了两个路由模块
app.use("/home", indexRouter);
app.use("/users", usersRouter);

// 处理404和500等错误
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
